import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Field, Balloon, Checkbox, Message } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import BranchSelect from 'components/branchSelect';
import exceed from 'utils/apimap';
import { getAllBranches, getDefaultBranch } from 'api';
import docs from 'utils/docs';
import intl from '../../../locale';

const { pathResource } = window.FORCE;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 4,
  },

  wrapperCol: {
    span: 20,
  },
};

export default class TagModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    onCancel: PropTypes.func,
    onClose: PropTypes.func,
    formSubmit: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      isModalOpen: false,
      submitting: false,
      branch: '',
      isNeedBranch: true,
      allBranches: [],
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  componentDidMount() {
    this.getBranches();
  }

  getBranches = () => {
    const { onChange, projectId } = this.props;
    Promise.all([getAllBranches(projectId), getDefaultBranch(projectId)])
      .then((results) => {
        const allBranches = results[0] ? results[0].slice(1) : [];
        const defaultBranch = results[1] ? results[1].default_branch : '';
        this.setState({
          allBranches,
          branch: defaultBranch,
        });

        onChange && onChange(defaultBranch);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.onClose();
  };

  onHandleSubmit = () => {
    if (this.state.submitting) return;
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        if (!this.state.isNeedBranch) {
          this.mergeCommit(this.state.branch);
        } else {
          this.createBranchByCommit();
        }
      } else {
        this.setState({ submitting: false });
      }
    });
  };

  mergeCommit = (branch_name, cb) => {
    const { sha, projectId } = this.props;
    exceed
      .fetch({
        api: 'commit.cherry_pick',
        params: { projectId: projectId || pathResource.id, sha },
        data: {
          branch: branch_name,
        },
      })
      .then(() => {
        this.setState({
          submitting: false,
        });

        if (cb) {
          cb();
        } else {
          Message.success({
            title: intl.get(
              {
                id: 'code-assets.commitDetail.cherryPickModal.CherryPickIsSubmittedTo',
                defaultMessage: '提交成功 Cherry-pick 到 {branchName} 分支',
              },
              { branchName: branch_name },
            ),
          });
        }
        this.onClose();
      })
      .fail((res) => {
        // 失败状态下 exceed 会拦截错误信息弹出。// 这里也会弹窗二次一模一样的错误信息
        if (res.status !== 403) {
          try {
            Message.error({
              title: JSON.parse(res.response).message,
            });
          } catch (error) {
            console.error(error);
          }
        }
        this.setState({ submitting: false });
      });
  };

  getBranchName = (cb) => {
    const { sha, projectId } = this.props;
    exceed
      .fetch({
        api: 'commit.options_branch_name',
        params: { projectId: projectId || pathResource.id, sha },
        data: {
          option: 'cherry-pick',
        },
      })
      .then((result) => {
        cb && cb(result.newBranchName);
      })
      .fail(() => {
        this.setState({
          submitting: false,
        });
      });
  };

  createBranchByCommit = () => {
    const { onChange, projectId } = this.props;
    const { branch } = this.state;
    this.getBranchName((branch_name) => {
      exceed
        .fetch({
          api: 'project.branches.post.associateTask',
          data: {
            project_id: projectId || pathResource.id,
            branch_name,
            ref: branch,
          },
        })
        .then(() => {
          this.mergeCommit(branch_name, () => {
            onChange &&
              onChange({
                createMrModalOpen: true,
                sourceBranch: branch_name,
                targetBranch: branch,
              });
          });
        })
        .fail(() => {
          this.setState({
            submitting: false,
          });
        });
    });
  };

  handleBranchChange = (value) => {
    this.setState({
      branch: value,
    });
  };

  handleCheckboxChange = (checked) => {
    this.setState({
      isNeedBranch: checked,
    });
  };

  render() {
    const { field } = this;
    const { branch, isNeedBranch, allBranches } = this.state;
    const { projectId } = this.props;
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            visible
            onClose={this.onClose}
            onCancel={this.onClose}
            okProps={{
              loading: this.state.submitting,
            }}
            onOk={this.onHandleSubmit}
            title={
              <div>
                Cherry-pick
                <Balloon
                  closable={false}
                  trigger={
                    <ButtonIcon
                      type="secondary"
                      name="question-line"
                      style={{ marginLeft: 4, display: 'inline-block' }}
                    />
                  }
                  align="t"
                >
                  {intl.get({
                    id: 'code-assets.commitDetail.cherryPickModal.HowToUse',
                    defaultMessage: '如何使用',
                  })}
                  <a target="_blank" href={docs('cherry-pick')} rel="noreferrer">
                    Cherry-pick
                  </a>{' '}
                  ？
                </Balloon>
              </div>
            }
            style={{
              width: '500px',
            }}
          >
            <Form labelAlign="top" field={field} className="cherry-pick-form">
              <FormItem
                label={intl.get({
                  id: 'code-assets.commitDetail.cherryPickModal.SelectTheTargetBranch',
                  defaultMessage: '请选择目标分支',
                })}
                required
                {...formItemLayout}
              >
                <BranchSelect
                  allBranches={allBranches}
                  value={branch}
                  projectId={projectId || pathResource.id}
                  onChange={this.handleBranchChange}
                  style={{ width: '50%' }}
                />
              </FormItem>
              <FormItem label="" {...formItemLayout}>
                <Checkbox checked={isNeedBranch} onChange={this.handleCheckboxChange}>
                  {intl.get({
                    id: 'code-assets.commitDetail.cherryPickModal.CreateANewBranchAnd',
                    defaultMessage: '创建一个新分支，并发起合并请求评审本次变更',
                  })}
                </Checkbox>
              </FormItem>
            </Form>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
